package org.example.other;

import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;

public class EvoSuiteTestGenerator {

    private static final String PROCESSED_CLASSES_FILE = "evosuite_processed_classes.txt"; // 用于记录已处理类的文件

    public static void main(String[] args) throws IOException {
        Path classesDir = Paths.get("target/classes"); // 目标类文件目录
        if (!Files.exists(classesDir)) {
            System.out.println("Classes directory not found!");
            return;
        }

        // 1. 读取所有类
        List<String> allClasses = Files.walk(classesDir)
                .filter(path -> path.toString().endsWith(".class"))
                .map(classesDir::relativize)
                .map(path -> path.toString().replace(File.separator, ".").replace(".class", ""))
                .collect(Collectors.toList());

        // 2. 读取已处理类记录
        Set<String> processedClasses = new HashSet<>();
        Path processedFile = Paths.get(PROCESSED_CLASSES_FILE);
        if (Files.exists(processedFile)) {
            processedClasses.addAll(Files.readAllLines(processedFile));
        }

        // 3. 过滤出未生成测试的类
        List<String> classesToProcess = allClasses.stream()
                .filter(className -> !processedClasses.contains(className))
                .collect(Collectors.toList());

        // 4. 为每个未处理的类生成测试
        for (String className : classesToProcess) {
            System.out.println("Generating tests for: " + className);

            // 提取简单类名
            String simpleClassName = className.substring(className.lastIndexOf('.') + 1);

            // 调用 EvoSuite
            ProcessBuilder processBuilder = new ProcessBuilder(
                    "java",
                    "-jar",
                    "lib/evosuite-1.2.0.jar", // EvoSuite 的 JAR 文件路径
                    "-class",
                    className, // 目标类
                    "-projectCP",
                    "target/classes"
            );

            processBuilder.inheritIO();
            try {
                Process process = processBuilder.start();
                process.waitFor();

                // 5. 将生成成功的类名追加到记录文件
                Files.write(processedFile, (className + System.lineSeparator()).getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            } catch (Exception e) {
                System.err.println("Failed to generate tests for: " + className);
                e.printStackTrace();
            }
        }

        System.out.println("EvoSuite test generation completed.");
    }
}
